<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="账单编号" prop="billNo">
        <el-input v-model="queryParams.billNo" placeholder="请输入账单编号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="老人姓名" prop="elderName">
        <el-input v-model="queryParams.elderName" placeholder="请输入" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="老人身份证号" prop="elderIdCard">
        <el-input v-model="queryParams.elderIdCard" placeholder="请输入" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 账单状态筛选 -->
    <el-button-group>
      <el-button :type="activeStatus === '' ? 'primary' : 'default'" @click="handleStatusChange('')">全部</el-button>
      <el-button :type="activeStatus === '0' ? 'primary' : 'default'" @click="handleStatusChange('0')">未支付</el-button>
      <el-button :type="activeStatus === '1' ? 'primary' : 'default'" @click="handleStatusChange('1')">已支付</el-button>
      <el-button :type="activeStatus === '2' ? 'primary' : 'default'" @click="handleStatusChange('2')">已关闭</el-button>
    </el-button-group>

    <!-- 生成月度账单按钮 -->
    <el-button type="primary" plain icon="Plus" class="generate-btn" @click="openGenerateDialogFn">
      生成月度账单
    </el-button>

    <!-- 月度账单弹窗 -->
    <el-dialog v-model="openGenerateDialog" :title="title" width="600px" append-to-body>
      <el-form ref="formRef" :model="form" label-width="100px">
        <el-form-item label="老人姓名" prop="elderId">
          <el-select v-model="form.elderId" placeholder="请选择">
            <el-option v-for="item in elderList" :key="item.id" :label="item.elderName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="账单月份" prop="billMonth">
          <el-date-picker
            v-model="form.billMonth"
            type="month"
            placeholder="请选择账单月份"
            format="YYYY-MM"
            value-format="YYYY-MM"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="openGenerateDialog = false">取消</el-button>
        <el-button type="primary" @click="handleGenerateConfirm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 入账列表 -->
    <el-table v-loading="loading" :data="billListList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center">
        <template #default="scope">{{ scope.$index + 1 }}</template>
      </el-table-column>
      <el-table-column label="账单编号" align="center" prop="billNo" />
      <el-table-column label="账单类型" align="center" prop="billType" :formatter="formatterBillType" />
      <el-table-column label="账单月份" align="center" prop="billMonth" />
      <el-table-column label="老人姓名" align="center" prop="elderName" />
      <el-table-column label="老人身份证号" align="center" prop="elderIdCard" />
      <el-table-column label="账单金额" align="center" prop="billAmount" />
      <el-table-column label="应付金额" align="center" prop="payableAmount" />
      <el-table-column label="支付截止时间" align="center" prop="paymentDeadline" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.paymentDeadline, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="账单状态" align="center" prop="billStatus" :formatter="formatterBillStatus" />
      <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createdAt, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button type="primary" text :disabled="isPayDisabled(scope.row)" @click="handlePay(scope.row)">支付</el-button>
          <el-button type="danger" text :disabled="isCancelDisabled(scope.row)" @click="openCancelDialog(scope.row)">取消</el-button>
          <el-button type="info" text :disabled="isViewDisabled(scope.row)" @click="handleView(scope.row)">查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 上传支付凭证弹窗 -->
    <el-dialog title="上传支付凭证" v-model="payDialogVisible" width="600px">
      <el-form>
        <el-form-item label="支付方式">
          <el-select v-model="payMethod" placeholder="请选择" style="width:100%">
            <el-option label="支付宝" value="alipay" />
            <el-option label="微信支付" value="wechat" />
            <el-option label="银行卡" value="bank" />
          </el-select>
        </el-form-item>

        <el-form-item label="支付凭证">
          <el-upload
            class="custom-upload"
            :auto-upload="true"
            :show-file-list="false"
            :headers="headers"
            :action="uploadUrl"
            accept="image/png,image/jpg,image/jpeg"
            :on-success="handleUploadSuccess"
          >
            <div class="upload-area">
              <img v-if="imageUrl" :src="imageUrl" class="uploaded-image" alt="支付凭证" />
              <div v-else class="upload-placeholder">
                <i class="el-icon-plus"></i>
                <div class="tip">点击上传图片</div>
              </div>
            </div>
          </el-upload>
          <div class="help-text">图片大小不超过2M，仅支持PNG、JPG、JPEG格式</div>
        </el-form-item>

        <el-form-item label="支付备注">
          <el-input
            v-model="remark"
            placeholder="请输入"
            maxlength="50"
            show-word-limit
            style="width: 100%; height: 80px;"
            :rows="3"
            type="textarea"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="payDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handlePayConfirm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 取消原因弹窗 -->
    <el-dialog title="填写取消原因" v-model="cancelDialogVisible" width="500px">
      <el-form ref="cancelFormRef" :model="cancelForm" label-width="120px">
        <el-form-item label="取消原因">
          <el-input
            v-model="cancelForm.reason"
            type="textarea"
            maxlength="100"
            show-word-limit
            placeholder="请输入取消原因（最多100个字符）"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancelDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCancelConfirm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script setup>
import { ref, reactive, toRefs, getCurrentInstance, nextTick } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { getToken } from "@/utils/auth";
import { listBillList, updateBillList } from "@/api/finance/billList";
import { addPayment } from "@/api/pay/payment";
import { ElderListCheckIn } from "@/api/elder/elder";

const { proxy } = getCurrentInstance();
const router = useRouter();
const uploadUrl = "http://localhost:8080/common/upload";
const headers = { Authorization: "Bearer " + getToken() };
const imageUrl = ref("");

function handleUploadSuccess(res) {
  if (res.code === 200) imageUrl.value = res.url;
  else ElMessage.error("上传失败");
}
function handlePay(row) {
  currentBill.value = row;   // 保存当前账单信息
  payMethod.value = "";      // 重置支付方式
  remark.value = "";         // 重置备注
  imageUrl.value = "";       // 重置图片
  payDialogVisible.value = true; // 打开支付弹窗
}

const openGenerateDialog = ref(false);
const activeStatus = ref("");
const billListList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const title = ref("");
const elderList = ref([]);
const payDialogVisible = ref(false);
const payMethod = ref("");
const remark = ref("");
const cancelDialogVisible = ref(false);
const cancelForm = reactive({ reason: "" });
const currentBill = ref(null);

const buttonStatusMap = {
  0: { 0: { pay: false, cancel: false, view: false }, 1: { pay: true, cancel: true, view: false }, 2: { pay: true, cancel: true, view: false } },
  1: { 0: { pay: true, cancel: false, view: false }, 1: { pay: true, cancel: true, view: false }, 2: { pay: true, cancel: true, view: false } },
};
const billTypeMap = { 0: "月度账单", 1: "服务账单" };
const billStatusMap = { 0: "待支付", 1: "已支付", 2: "已关闭" };

const formatterBillType = (row) => billTypeMap[row.billType] || "未知";
const formatterBillStatus = (row) => billStatusMap[row.billStatus] || "未知";
const isPayDisabled = (row) => buttonStatusMap[row.billType]?.[row.billStatus]?.pay ?? true;
const isCancelDisabled = (row) => buttonStatusMap[row.billType]?.[row.billStatus]?.cancel ?? true;
const isViewDisabled = (row) => buttonStatusMap[row.billType]?.[row.billStatus]?.view ?? false;

const handleView = (row) => {
  nextTick(() => {
    router.push({ path: "/finance/bill/billDetail", query: { billNo: row.billNo } });
  });
};

const openCancelDialog = (row) => {
  currentBill.value = row;
  cancelForm.reason = "";
  cancelDialogVisible.value = true;
};

async function handleCancelConfirm() {
  if (!cancelForm.reason) return ElMessage.warning("请填写取消原因");

  const payload = {
    id: currentBill.value.id,
    billNo: currentBill.value.billNo,
    billStatus: 2,
    extend2: cancelForm.reason,
  };

  try {
    const res = await updateBillList(payload);
    if (res.code === 200) {
      ElMessage.success("账单已取消");
      cancelDialogVisible.value = false;
      getList();
    } else {
      ElMessage.error(res.msg || "取消失败");
    }
  } catch (error) {
    console.error("取消请求异常:", error);
    ElMessage.error("取消失败，请稍后重试");
  }
}

async function handlePayConfirm() {
  if (!payMethod.value) return ElMessage.warning("请选择支付方式");
  if (!imageUrl.value) return ElMessage.warning("请上传支付凭证图片");

  const payload = {
    bizOrderNo: currentBill.value?.billNo,
    payChannel: payMethod.value,
    extend1: imageUrl.value,
    remark: remark.value,
  };

  try {
    const res = await addPayment(payload);
    if (res.code === 200) {
      ElMessage.success("支付凭证提交成功！");
      payDialogVisible.value = false;
      await updateBillList({
        id: currentBill.value.id,
        billNo: currentBill.value.billNo,
        billStatus: 1,
      });
      getList();
    } else {
      ElMessage.error(res.msg || "提交失败");
    }
  } catch (error) {
    console.error("支付请求异常:", error);
    ElMessage.error("提交异常，请稍后再试");
  }
}

const data = reactive({
  form: {},
  queryParams: { pageNum: 1, pageSize: 10, billNo: null, billStatus: null },
});
const { queryParams, form } = toRefs(data);

function openGenerateDialogFn() {
  form.value = {};
  openGenerateDialog.value = true;
  title.value = "生成月度账单";
  ElderListCheckIn().then((res) => (elderList.value = res.data));
}

function getList() {
  loading.value = true;
  listBillList(queryParams.value).then((res) => {
    billListList.value = res.rows;
    total.value = res.total;
    loading.value = false;
  });
}

function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

function handleStatusChange(status) {
  activeStatus.value = status;
  queryParams.value.billStatus = status === "" ? null : status;
  getList();
}

getList();
</script>

<style scoped>
.generate-btn {
  margin-left: 15px;
  float: right;
}

/* 上传区域优化 */
.custom-upload {
  display: inline-block;
  cursor: pointer;
}

.upload-area {
  position: relative;
  width: 120px;
  height: 120px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #999;
  overflow: hidden;
}

.upload-area:hover {
  border-color: #409eff;
}

.uploaded-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 6px;
}

.upload-placeholder {
  text-align: center;
}

.upload-placeholder .el-icon-plus {
  font-size: 28px;
  margin-bottom: 6px;
  color: #aaa;
}

.upload-placeholder .tip {
  font-size: 13px;
  color: #aaa;
}

.help-text {
  margin-left: 20px;
  margin-top: 8px;
  font-size: 12px;
  color: #999;
}
</style>
